#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

#include "debug.h"
#include "globals.h"
#include "memory.h"

static volatile memaddr_t * current_addr = NULL;

memaddr_t * remap_memory(unsigned int base_address)
{
    memaddr_t * base_addr = NULL;
    int file_descriptor;
    int page_size = getpagesize();
    
    file_descriptor = open("/dev/mem", O_RDWR | O_SYNC);
    if (file_descriptor < 0)
    {
        perror("REMAP_MEMORY:");
        return NULL;
    }
    
    base_addr = (memaddr_t *)mmap(0, 
                                  page_size, 
                                  PROT_READ | PROT_WRITE,
                                  MAP_SHARED,
                                  file_descriptor,
                                  base_address);
    if (base_addr == (memaddr_t *)MAP_FAILED)
    {
        fprintf(stderr, "REMAP_MEMORY: mmap() failed.\n");
        close(file_descriptor);
        return NULL;
    }
    
    current_addr = base_addr;
    close(file_descriptor);
    
    return base_addr;
}

memaddr_t * map_memory_register(memaddr_t * addr)
{
    if (current_addr != NULL)
    {
        addr = (memaddr_t *)current_addr;
        current_addr++;
        return addr;
    }
    
    return NULL;
}

